package com.cuiweiyou.uiautomator20;

import android.graphics.Rect;
import android.support.test.uiautomator.By;
import android.support.test.uiautomator.Configurator;
import android.support.test.uiautomator.UiDevice;
import android.support.test.uiautomator.UiObject;
import android.support.test.uiautomator.UiObject2;
import android.support.test.uiautomator.UiObjectNotFoundException;
import android.support.test.uiautomator.UiSelector;
import android.support.test.uiautomator.Until;
import android.util.Log;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import java.util.Random;

/**
 * www.gaohaiyan.com
 */
public class TestUtilCtrl {
    private TestUtilCtrl() {
    }

    public static void requestPermission(UiDevice device) {
        try {

            String result1 = device.executeShellCommand("pm grant com.cuiweiyou.uiautomator20 android.permission.WRITE_EXTERNAL_STORAGE");
            String result2 = device.executeShellCommand("pm grant com.cuiweiyou.uiautomator20 android.permission.READ_EXTERNAL_STORAGE");

            UtilLogs.saveLog("申请写sd卡权限shell 反馈：" + result1);
            UtilLogs.saveLog("申请读sd卡权限shell 反馈：" + result2);
        } catch (IOException e) {
            e.printStackTrace();
            UtilLogs.saveLog("申请读sd卡权限shell err：" + e.getMessage());
        }
    }

    public static void launcherWechatApp(UiDevice device, String taskName) {
        try {
            String result = device.executeShellCommand("am start -n com.tencent.mm/com.tencent.mm.ui.LauncherUI");
            UtilLogs.saveLog("启动微信shell，" + taskName + " 反馈：" + result);
        } catch (IOException e) {
            e.printStackTrace();
            UtilLogs.saveLog("启动微信失败：" + e.getMessage());
        }
    }

    /**
     * 切换首页的标签页
     *
     * @param tabName 微信、通讯录、发现、我
     */
    public static void switchTab(UiDevice device, String tabName) {
        String home_tab_item = ManagerViewID.getInstance().getSelfViewId(ManagerViewID.VIEW_ID_NAME_home_tab_item);

        device.wait(Until.hasObject(By.text(tabName)), 5000);

        UiObject2 tabObject = device.findObject(By.text(tabName));
        if ("微信".equals(tabName)) {
            if (null == home_tab_item) {
                tabObject = device.findObject(By.res("com.tencent.mm", "cw5"));
                UtilLogs.saveLog("切换到：" + tabName + " 1ID：cw5");
            } else {
                String id = home_tab_item.replace("com.tencent.mm:id/", "");
                tabObject = device.findObject(By.res("com.tencent.mm", id));
                UtilLogs.saveLog("切换到：" + tabName + " 2ID：" + id);
            }
        }
        if (null != tabObject) {
            tabObject.click();
            UtilLogs.saveLog("切换到：" + tabName + " 1点击了");
        } else {
            UiObject object = device.findObject(new UiSelector().text(tabName));
            if ("微信".equals(tabName)) {
                if (null == home_tab_item) {
                    object = device.findObject(new UiSelector().resourceId("com.tencent.mm:id/cw5"));
                    UtilLogs.saveLog("切换到：" + tabName + " 控件：cw5");
                } else {
                    object = device.findObject(new UiSelector().resourceId(home_tab_item));
                    UtilLogs.saveLog("切换到：" + tabName + " 控件：" + home_tab_item);
                }
            }
            try {
                if (object.exists()) {
                    object.click();
                    UtilLogs.saveLog("切换到：" + tabName + " 2点击了");
                }
            } catch (UiObjectNotFoundException e) {
                e.printStackTrace();
                UtilLogs.saveLog("切换到：" + tabName + " 失败：" + e.getMessage());
            }
        }

        UtilLogs.saveLog("点击切换到便签：" + tabName);
    }

    /**
     * 好友到详细信息界面
     *
     * @param flag 0-主动请求加人到朋友，1-已经是朋友关系的，2-好友查找
     * @return 返回资料数组：0-微信号，1-备注名，2-昵称
     */
    public static String[] getFriendDetails(UiDevice device, int flag) {
        UtilLogs.saveLog("查看详细资料，来源页面：" + flag);

        String detail_name_note = ManagerViewID.getInstance().getSelfViewId(ManagerViewID.VIEW_ID_NAME_detail_name_note);
        String detail_name_nick = ManagerViewID.getInstance().getSelfViewId(ManagerViewID.VIEW_ID_NAME_detail_name_nick);
        String detail_name_wxid = ManagerViewID.getInstance().getSelfViewId(ManagerViewID.VIEW_ID_NAME_detail_name_wxid);

        String[] result = new String[3];
        result[0] = "";
        result[1] = "";
        result[2] = "";

        device.wait(Until.hasObject(By.textContains("详细资料")), 5000);

        Boolean hasWxidObject = device.wait(Until.hasObject(By.textContains("微信号:")), 5000);
        if (hasWxidObject) {
            UiObject object = device.findObject(new UiSelector().textContains("微信号:"));
            String wxid = null;
            try {
                wxid = object.getText().replace("微信号:", "");
                result[0] = wxid;
                UtilLogs.saveLog("朋友详细信息界面，有关键字 '微信号:'，得到：" + result[0]);
            } catch (UiObjectNotFoundException e) {
                e.printStackTrace();
                UtilLogs.saveLog("朋友详细信息界面，err：" + e.getMessage());
            }
        } else {
            UtilLogs.saveLog("朋友详细信息界面，没有关键字 '微信号:'");
            UiObject2 object = null;
            try {
                object = device.findObject(By.res(detail_name_wxid));
            } catch (NullPointerException e) {
                UtilLogs.saveLog("朋友详细信息界面，没有关键字 '微信号'的控件'" + e.getMessage());
            }

            if (null != object) {
                String text = object.getText();
                UtilLogs.saveLog("朋友详细信息界面，控件id '" + detail_name_wxid + "'，得到1：" + text);
                if (null != text) {
                    result[0] = text.replace("微信号:", "");
                    UtilLogs.saveLog("朋友详细信息界面，控件id '" + detail_name_wxid + "'，得到2：" + result[0]);
                } else {
                    UtilLogs.saveLog("朋友详细信息界面，控件id '" + detail_name_wxid + "'，没得到2：null");
                }
            } else {
                UtilLogs.saveLog("朋友详细信息界面，没有控件id '" + detail_name_wxid + "'");
            }
        }
        UtilLogs.saveLog("ctrl获取好友的微信号：" + result[0]);

        Boolean hasNoteNameObject;
        if (null == detail_name_note) {
            hasNoteNameObject = device.wait(Until.hasObject(By.res("com.tencent.mm", "u1")), 5000);
            UtilLogs.saveLog("朋友详细信息界面，等待备注名：u1");
        } else {
            String id = detail_name_note.replace("com.tencent.mm:id/", "");
            hasNoteNameObject = device.wait(Until.hasObject(By.res("com.tencent.mm", id)), 5000);
            UtilLogs.saveLog("朋友详细信息界面，等待备注名：id" + id);
        }
        if (hasNoteNameObject) {
            UiObject object;
            if (null == detail_name_note) {
                object = device.findObject(new UiSelector().resourceId("com.tencent.mm:id/u1"));
                UtilLogs.saveLog("朋友详细信息界面，查找备注名1：com.tencent.mm:id/u1");
            } else {
                object = device.findObject(new UiSelector().resourceId(detail_name_note));
                UtilLogs.saveLog("朋友详细信息界面，查找备注名2：" + detail_name_note);
            }

            String noteName = null;
            try {
                noteName = object.getText();
                result[1] = noteName;
                UtilLogs.saveLog("朋友详细信息界面，查找备注名3：" + result[1]);
            } catch (UiObjectNotFoundException e) {
                e.printStackTrace();
                UtilLogs.saveLog("朋友详细信息界面，查找备注名 err：" + e.getMessage());
            }
        } else {
            UtilLogs.saveLog("朋友详细信息界面，等待备注名控件：无");
        }
        UtilLogs.saveLog("ctrl获取好友的备注名：" + result[1]);

        Boolean hasNickNameObject;
        if (null == detail_name_nick) {
            hasNickNameObject = device.wait(Until.hasObject(By.res("com.tencent.mm", "ax3")), 5000);
            UtilLogs.saveLog("朋友详细信息界面，等待昵称控件：ax3");
        } else {
            String id = detail_name_nick.replace("com.tencent.mm:id/", "");
            hasNickNameObject = device.wait(Until.hasObject(By.res("com.tencent.mm", id)), 5000);
            UtilLogs.saveLog("朋友详细信息界面，等待昵称控件：id=" + id);
        }
        if (hasNickNameObject) {
            UiObject object;
            if (null == detail_name_nick) {
                object = device.findObject(new UiSelector().resourceId("com.tencent.mm:id/ax3"));
                UtilLogs.saveLog("朋友详细信息界面，查找昵称控件1：com.tencent.mm:id/ax3");
            } else {
                object = device.findObject(new UiSelector().resourceId(detail_name_nick));
                UtilLogs.saveLog("朋友详细信息界面，查找昵称控件2：" + detail_name_nick);
            }

            String nickName = null;
            try {
                nickName = object.getText();
                result[2] = nickName;
                UtilLogs.saveLog("朋友详细信息界面，获取昵称1：" + result[2]);
            } catch (UiObjectNotFoundException e) {
                e.printStackTrace();
                UtilLogs.saveLog("朋友详细信息界面，获取昵称err：" + e.getMessage());
            }
        }
        UtilLogs.saveLog("ctrl获取好友的昵称：" + result[2]);

        return result;
    }

    /**
     * 手指头从屏幕顶部向底部滑动，ListView的内容滚动到顶部item
     */
    public static void swipeListViewToTopItem(UiDevice device) {
        int start_x = 50;
        int start_y = 200;
        int end_x = 50;
        int end_y = device.getDisplayHeight() - 200;
        int stepTop = 50;
        device.swipe(start_x, start_y, end_x, end_y, stepTop);
        UtilLogs.saveLog("滚动到屏幕顶部------");
    }

    /**
     * 手指头从屏幕底部向顶部滑动
     */
    public static void swipeListViewToBottomItem(UiDevice device) {
        int start_x = 50;
        int start_y = device.getDisplayHeight() - 200;
        int end_x = 50;
        int end_y = 200;
        int stepBottom = 50;
        device.swipe(start_x, start_y, end_x, end_y, stepBottom);
        UtilLogs.saveLog("滚动到屏幕底部---------");
    }

    /**
     * 控件长按操作
     *
     * @param uiObject
     * @throws UiObjectNotFoundException
     */
    public static void longClick(UiDevice device, UiObject2 uiObject) {
        Rect bounds = uiObject.getVisibleBounds();
        int x = bounds.centerX();
        int y = bounds.centerY();
        device.swipe(x, y, x, y, 50);
        UtilLogs.saveLog("长按控件：x=" + x + "，y=" + y);
    }

    /**
     * 双击
     *
     * @param object2
     */
    public static void doubleClick(UiObject2 object2) {
        long timeout = Configurator.getInstance().getActionAcknowledgmentTimeout();

        int timeDiff = new Random().nextInt(10) + 20;
        Configurator.getInstance().setActionAcknowledgmentTimeout(timeDiff);

        object2.click();
        UtilLogs.saveLog("双击：1");
        object2.click();
        UtilLogs.saveLog("双击：2");

        UtilLogs.saveLog("双击控件：12");

        Configurator.getInstance().setActionAcknowledgmentTimeout(timeout);
    }

    public static String showCurrentActivity(UiDevice device, String note) {
        String runningActivity = "";
        try {
            runningActivity = device.executeShellCommand("dumpsys activity");
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(new ByteArrayInputStream(runningActivity.getBytes(Charset.forName("utf8"))), Charset.forName("utf8")));
            String line;
            while (null != (line = bufferedReader.readLine())) {
                if (line.contains("mFocusedActivity")) {
                    runningActivity = line.replaceFirst("mFocusedActivity: ActivityRecord\\{", "").replaceFirst("\\}", "");
                    UtilLogs.saveLog("，当前显示的-Activity：" + runningActivity);
                    break;
                }
            }

        } catch (IOException e) {
            e.printStackTrace();
        }

        return runningActivity;
    }

}
